package users

import (
	"context"
	"product/common/validator"

	"product/authorization/serve/internal/svc"
	"product/authorization/serve/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CheckEmailExistLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewCheckEmailExistLogic Check valid email
func NewCheckEmailExistLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CheckEmailExistLogic {
	return &CheckEmailExistLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CheckEmailExistLogic) CheckEmailExist(req *types.CheckEmailExistReq) (resp *types.CheckEmailExistResp,
	err error) {
	// 首先判断是否是合法邮箱
	if !validator.IsEmail(req.Email) {
		return &types.CheckEmailExistResp{
			Message: "邮箱不合法",
			Ok:      false,
		}, nil
	}
	exist, err := l.svcCtx.UsersModel.CheckEmailExists(l.ctx, req.Email)
	if err == nil && exist {
		return &types.CheckEmailExistResp{
			Message: "邮箱已存在",
			Ok:      false,
		}, nil
	}

	return &types.CheckEmailExistResp{
		Message: "邮箱可用",
		Ok:      true,
	}, nil
}
